package com.na.game.engine.ui;

import com.na.game.engine.GameManager;
import com.na.game.engine.event.EventListener;
import com.na.game.engine.event.Updater;
import com.na.game.engine.event.impl.KeyEvent;
import com.na.game.engine.event.impl.TouchEvent;
import com.na.game.engine.graphics.Graphics;
import com.na.game.engine.graphics.Painter;
import com.na.game.engine.opengl.GLTextureManager;
import com.na.game.engine.resource.Destruction;
import com.na.game.engine.util.GameConfig;
import com.na.game.engine.widget.impl.Container;

public abstract class UI implements Painter, Updater, EventListener, Destruction {
	
	protected Container uiWidget;
	protected Painter painter;
	protected boolean transparent;
	protected boolean validKeyEvent;
	
	public UI() {
	}
	
	public UI(Container uiWidget) {
		this.uiWidget = uiWidget;
	}
	
	public void setWidget(Container w) {
		uiWidget = w;
	}
	
	public void setPainter(Painter painter) {
		this.painter = painter;
	}

	public boolean isTransparent() {
		return transparent;
	}

	public void setTransparent(boolean transparent) {
		this.transparent = transparent;
	}

	@Override
	public boolean onKey(KeyEvent event) {
		if (event.keyCode == android.view.KeyEvent.KEYCODE_BACK) {
			switch (event.action) {
				case android.view.KeyEvent.ACTION_DOWN:
					validKeyEvent = true;
					return true;
				case android.view.KeyEvent.ACTION_UP:
					if (validKeyEvent) {
						validKeyEvent = false;
						GameManager.get(UIManager.class).popUI();
					}
					return true;
			}
		}
		return false;
	}

	@Override
	public boolean onTouch(TouchEvent event) {
		return (uiWidget != null && uiWidget.getAbsBound().contains(event.x, event.y) && uiWidget.onTouch(event));
	}

	@Override
	public void update() {
		if (uiWidget != null) {
			uiWidget.update();
		}
	}

	@Override
	public void paint(Graphics g) {
		if (uiWidget != null) {
			uiWidget.paint(g);
		}
		if (painter != null) {
			painter.paint(g);
		}
	}
	
	@Override
	public void destroy() {
		if (GameConfig.useOpenGL) {
			GLTextureManager.clear();
		}
	}
	
	public abstract void init();
	
}
